const express = require('express');
const Busboy = require('busboy')
const path = require('path')
const fs = require('fs')
// 引入跨域插件
const cors = require('cors'); 

const app = express();
const port = process.env.PORT || 5000;
const NodeStl = require("node-stl");

// 解决跨域
app.use(cors());
app.use(express.static('client'));
app.use('/models/', express.static('models'));
app.use((req, res, next) => {
  //判断路径
  if (req.path !== '/' && !req.path.includes('.')) {
    res.set({
      'Access-Control-Allow-Credentials': true, //允许后端发送cookie
      'Access-Control-Allow-Origin': '*', //任意域名都可以访问,或者基于我请求头里面的域
      'Access-Control-Allow-Headers': 'X-Requested-With,Content-Type', //设置请求头格式和类型
      'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS',//允许支持的请求方式
      'Content-Type': 'application/json; charset=utf-8'//默认与允许的文本格式json和编码格式
    })
  }
  req.method === 'OPTIONS' ? res.status(204).end() : next()
})
//get stl
app.get('/express_backend', (req, res) => {
  let stl = new NodeStl(__dirname + '/models/mb.stl', { density: 1.248 });
  console.log(stl.volume + '平方厘米');
  console.log(stl.weight + 'GM');
  console.log(stl.boundingBox,'(mm)');
  console.log(stl.area,'(m)');
  console.log(stl.centerOfMass,'(mm)');
  res.send({
    data: {
      volume: stl.volume.toFixed(3),
      weight: stl.weight.toFixed(3),
      area: stl.area.toFixed(3)
    }
  })
});
//获取本机ip地址
function getIPAdress() {
  let interfaces = require('os').networkInterfaces();
  for (let devName in interfaces) {
    let iface = interfaces[devName];
    for (let i = 0; i < iface.length; i++) {
      let alias = iface[i];
      if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
        return alias.address;
      }
    }
  }
}

// 处理上传文件服务
app.post('/upload', (req, res) => {
  const busboy = new Busboy({ headers: req.headers });
  let fileName = null
  busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
    const saveTo = path.join(__dirname, 'models', filename);
    fileName = filename
    file.pipe(fs.createWriteStream(saveTo));
  });

  busboy.on('finish', function () {
    let stl = new NodeStl(__dirname + '/models/' + fileName, { density: 1.248 });
    // console.log(stl)
    res.send({
      code: 200,
      data: {
        volume: stl.volume.toFixed(3),
        weight: stl.weight.toFixed(3),
        area: stl.area.toFixed(3),
        file_url: 'http://' + getIPAdress() + '/models/' + fileName,
        url: 'http://' + getIPAdress() + ':5000?stl=' + fileName,
      }
    });
  });

  return req.pipe(busboy);
});


app.listen(port, () => console.log(`Connected port http://${getIPAdress()}:${port}`));